(function (undefined) {

    (function (factory) {
        "use strict";

        // amd module
        if (typeof define === "function" && define.amd) {
            define(["jquery", "widget" /*,其他脚本文件名称请在这里填写，如'echarts'*/], factory);
        }
        // global
        else {
            factory();
        }

    })
    (function ($, widget /*,其他脚本文件对外暴露接口请在这里填写，如'charts'*/) {
        "use strict";

        //关于组件配置说明，请见"开发者中心"，搜索"388.组件设计"

        //关于代码调试工具的使用说明，请见"开发者中心"，搜索"397.开发者工具使用文档"

        var Component = function (widgetIns, $widget, option, attr, css, auiCtx) {
            var context = this;


            context.widgetIns = widgetIns;
            context.$view = $widget;
            context.option = option;
            context.attr = attr;
            context.css = css;
            context.pageContext = auiCtx;

            //初始化
            context._init();

            //渲染样式
            //context._render();

            //绑定事件
            context._listen();
        };


        //在代码中声明的接口，必须在"接口"配置中配置好，详情见各个接口的注释
        //一定要配置某个组件接口，才能在"前端逻辑引擎"和"开发者中心"中，引用或查看该接口
        //**关于组件接口是否配置正确，可以保存组件配置后，打开"开发者中心"-->"组件"-->打开当前组件，查看组件接口是否配置正确**
        //打开调试工具，输入"auiCtx.variables.组件实例ID.接口名"，可以调试接口是否可行
        Component.prototype = Component.fn = {
            constructor: Component,
            version: 'AWOS 5.0.0.0_Stand GooFlow',
            content: null,
            //初始化（私有）
            _init: function (data) {
                var that = this;
                var $widget = this.$view,
                    html = [];

                //解析option、attr、css

                //使用$.fn.off().empty().append(html)可以避免调用$.fn.html(html)时导致的内存泄漏。
                $widget
                //使用empty方法释放DOM对象的内存
                    .empty()
                    //安全添加html元素
                    .append(html.join(''));
                var contentId = (parseInt(Math.random() * 10) - 0) + (Date.parse(new Date) - 0);
                $widget.append("<div id='" + contentId + "' style='margin:5px'></div>");
                var property = {
                    width: 1200,
                    height: 540,
                    toolBtns: ["system", "function", "interface", "scene"],
                    haveHead: true,
                    headLabel: true,
                    headBtns: ["new", "open", "save", "undo", "redo", "reload", "print"], //如果haveHead=true，则定义HEAD区的按钮
                    haveTool: true,
                    haveGroup: true,
                    useOperStack: true,
                    nodeWidth: 289,
                    nodeHeight: 52.1,
                    color: {
                        system: "",
                        function: "",
                        interface: "",
                        scene: ""
                    }
                };
                property.haveHead = this.option.showMenu;
                property.haveTool = this.option.showFunction;
                property.nodeWidth = this.option.nodeWH.nodeWidth ? this.option.nodeWH.nodeWidth : 289;
                property.nodeHeight = this.option.nodeWH.nodeHeight ? this.option.nodeWH.nodeHeight : 52.1;
                this._optionsColor(that, property);
                property.toolBtns
                if (this.option.menuConfig.add) {
                    property.headBtns[0] = "new";
                } else {
                    property.headBtns[0] = "";
                }
                if (this.option.menuConfig.open) {
                    property.headBtns[1] = "open";
                } else {
                    property.headBtns[1] = "";
                }
                if (this.option.menuConfig.save) {
                    property.headBtns[2] = "save";
                } else {
                    property.headBtns[2] = "";
                }
                if (this.option.menuConfig.undo) {
                    property.headBtns[3] = "undo";
                } else {
                    property.headBtns[3] = "";
                }
                if (this.option.menuConfig.redo) {
                    property.headBtns[4] = "redo";
                } else {
                    property.headBtns[4] = "";
                }
                if (this.option.menuConfig.reload) {
                    property.headBtns[5] = "reload";
                } else {
                    property.headBtns[5] = "";
                }
                if (this.option.menuConfig.print) {
                    property.headBtns[6] = "print";
                } else {
                    property.headBtns[6] = "";
                }

                var remark = {
                    cursor: "选择指针",
                    direct: "结点连线",
                    system: "系统",
                    "function": "功能",
                    "interface": "接口",
                    "scene": "场景"
                };
                this.content = $.createGooFlow($("#" + contentId), property);
                this.content.setNodeRemarks(remark);
                $('.ico_new').attr('title', '查看图例');
            },
            _optionsColor: function (that, property) {
                debugger;
                var toolBtns = property.toolBtns;
                toolBtns.forEach(function (item, index) {
                    var itemColor = item + "Color";
                    var prop = item;
                    property.color[prop + ""] = that.option.nodeColor[itemColor];
                })

            },
            _test: function () {
                console.log(new Date().toString());
            },
            //事件绑定（私有）
            _listen: function () {
                var $widget = this.$view;
                $widget.delegate('.GooFlow_item', 'click', function (event,$widget) {
                    var target = event.target,template=[],result=$(this).data('result');
                    Object.getOwnPropertyNames(result).forEach(function(item,index){
                        console.log(result[item]);
                        template.push('<p data-role="message" style="font-size: 1.2em"><i class="iconfont fa-data"></i>&nbsp;&nbsp;<span style="font-weight: bold">'+item+"</span>"+":"+result[item].toString().replace(/\n/g, '<br/>') + '</p>')
                    });
                    debugger;
                    app.modal({
                        title: '信息详情',
                        btnCancel: '取消',
                        content: '<div class="aui-ide-modal-content">' +template.join().replace(/,/g,'')+ '</div>',
                        isDialog: true,
                        isLargeModal: false,
                        init: function () {
                            var $body = $(this);
                            setTimeout(function () {
                                $body.prev().find('.close').off().remove();
                            }, 100);
                        }
                    });
                });
            },

            //渲染主题、样式（私有）
            _render: function () {
                var $widget = this.$view,
                    css = this.css,
                    style;

                //css样式配置渲染
                if (css && css.theme) {
                    //如果组件配置了类名主题，则要同时将类名加到组件相应位置上去
                    /*
                     * 如 ：if(css.theme['function']){
                         $button.removeClass().addClass('btn ' + css.theme['function']);
                     }*/
                }

                if (css && (style = css.style)) {
                }

            },
            _autoStructure: function (data) {
                var w = this.$view.find('.GooFlow_work').width();
                var h = this.$view.find('.GooFlow_work').height();
                var column = data.column ? data.column : {};
                var rowspan = column.length;
                var colspan = 0;
                for (var i = 0; i < column.length; i++) {
                    if (colspan < column[i].length) {
                        colspan = column[i].length;
                    }
                    ;
                }
                var width = ((2 * rowspan + 1) * 180) > w ? ((2 * rowspan + 1) * 180) : w;
                var height = ((2 * colspan + 1) * 40) > h ? ((2 * colspan + 1) * 40) : h;
                var initLeft = (width - ((2 * rowspan - 1) * 180)) / 2 - 60;
                for (var i = 0; i < column.length; i++) {
                    var colLen = column[i].length;
                    var initTop = (height - ((2 * colLen - 1) * 40)) / 2;
                    for (var j = 0; j < colLen; j++) {
                        column[i][j].width = 180;
                        column[i][j].height = 40;
                        column[i][j].top = initTop + j * 80;
                        column[i][j].left = initLeft + i * 260;
                        column[i][j].alt = true;
                    }
                }
                return data;
            },
            _handleObj: function (o_obj) {
                var n_obj = {};
                n_obj.title = o_obj.title;
                n_obj.nodes = {};
                n_obj.lines = o_obj.lines;
                n_obj.areas = {};
                n_obj.initNum = 44;
                for (var i = 0; i < o_obj.column.length; i++) {
                    for (var j = 0; j < o_obj.column[i].length; j++) {
                        var id = o_obj.column[i][j].id;
                        n_obj.nodes["" + id + ""] = o_obj.column[i][j];
                        n_obj.nodes["" + id + ""].message=n_obj.nodes["" + id + ""].id+'节点信息';
                    }
                }
                return n_obj;
            },
            _createDiv: function (context) {
                var $el = $("<div class='navigation' hidden=true><div id='title'><span>图&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;例</span></div></div>");
                var $content = $("<div id='layout'></div>");
                var temp = Object.getOwnPropertyNames(context.option.nodeColor);
                var arr = [];
                temp.forEach(function (item, index) {
                    if (item.indexOf('Color') != -1) {
                        arr.push(item);
                    }
                });
                arr.forEach(function (item, index) {
                    var $child = $("<div class='inner'><div class='inner-content'></div><div class='inner-left'></div></div>");
                    var color = context.option.nodeColor[item + ""];
                    $child.find('.inner-content').css({"background-color": color});
                    if (item.slice(0, -5) == 'function') {
                        $child.find('.inner-left').html('功能');
                    } else if (item.slice(0, -5) == 'scene') {
                        $child.find('.inner-left').html('场景');
                    } else if (item.slice(0, -5) == 'interface') {
                        $child.find('.inner-left').html('接口');
                    } else {
                        $child.find('.inner-left').html('系统');
                    }
                    $content.append($child);
                });
                for (var i = 0; i < 2; i++) {
                    var $child = $("<div class='inner'><div class='inner-content' style='background-color:#FFFFFF;color: #20A0FF'></div><div class='inner-left'></div></div>");
                    if (i == 0) {
                        $child.find('.inner-content').html('&nbsp;&nbsp;———————>');
                        $child.find('.inner-left').html('已发布');
                    } else {
                        $child.find('.inner-content').html('&nbsp;&nbsp;&nbsp;---------------->');
                        $child.find('.inner-left').html('未发布');
                    }
                    $content.append($child);
                }
                $el.append($content);
                context.$view.find('.GooFlow_head').after($el);
            },
            destroy: function () {
                this.$view.off().empty();
            },
            getValue: function () {
                return JSON.stringify(this.content.exportData());
            },
            setter: function (linkList) {
                /*
                 *   linkList=[{
                 *       name:'链接项1',
                 *       href:'id1
                 *   }]
                 * */
                var //模板
                    TEMPLATE = '<a data-href="_value_">_name_</a>',
                    //填充数据
                    html = [],
                    //中间变量
                    i, item,

                    $widget = this.$view;

                //清空上次的内容
                $widget.empty();

                if (linkList === 'auiAjaxText') {
                    //此处为 AWEB IDE 下 异步传输数据测试信号
                } else if (linkList && linkList.length) { //校验输入数据
                    for (i = -1; item = linkList[++i];) {
                        html.push(
                            TEMPLATE
                                .replace(/_name_/ig, item.name)
                                .replace(/_value_/ig, item.href)
                        );
                    }
                    //填充内容
                    $widget.append(html.join(''));
                }
            },

            refresh: function (data) {
                var that = this;
                if (!(data.nodes)) {
                    var temp = this._autoStructure(data);
                    var result = this._handleObj(temp);
                }
                if (typeof (result) == 'object') {
                    if (this != undefined) {
                        if (this.$view.find('.GooFlow_item').length) {
                            this.content.clearData();
                        }
                        this.content.loadData(result);
                    }
                }
                /*                this.$view.find('.GooFlow_item').on('click', function () {
                                    debugger;
                                    app.alert('');
                                });*/
                this.content.onItemDel = function (id, type) {
                    this.blurItem();
                    return true;
                }
                this.content.onPrintClick = function () {
                    window.print()
                };
                this.content.onBtnNewClick = function () {
                    if ($('.navigation').length <= 0) {
                        that._createDiv(that);
                    }
                    if ($('.navigation').attr('hidden')) {
                        $(".navigation").slideDown();
                        $('.navigation').attr('hidden', false);
                    } else {
                        $(".navigation").slideUp();
                        $('.navigation').attr('hidden', true);
                    }
                };
            },
            validateHandler: function (value) {
                return {
                    result: true, //校验结果
                    value: value, //传输的格式
                    errorMsg: '' //校验失败的错误提示
                }
            },
            behavior: function (result, input1, input2, condition) {
                this[result ? 'hide' : 'show']();
            },
            show: function () {
                this.$view.removeClass('hide');
            },
            hide: function () {
                this.$view.addClass('hide');
            }
        };

        widget.custom.gooflow = function () {
            var widgetIns, eventHandler,
                $widget, option, attr, css, auiCtx;

            if (arguments[0].version) {
                widgetIns = arguments[0];

                new Component(
                    widgetIns,
                    widgetIns[0].$widget.children('[data-widget-type]'),
                    widgetIns.option(),
                    widgetIns.attr(),
                    widgetIns.css(),
                    null
                );
                return widget;
            } else {
                $widget = arguments[0];
                option = arguments[1];
                attr = arguments[2];
                css = arguments[3];
                auiCtx = arguments[4];

                //运行时代码Start
                return new Component(null, $widget, option, attr, css, auiCtx);
                //运行时代码End
            }
        };
    });
})();
